<template>
  <div class="full-container">
    <div style="display: flex; flex-direction: column; gap: 12px">
      <el-card>
        <template #header>
          <div class="card-header">
            <span>任务队列</span>
          </div>
        </template>
        <div style="height: 300px">
          <div style="display: flex; flex-direction: row">
            <el-button type="primary" @click="addTask">
              <i class="el-icon iconfont icon-zhuanshukefu"></i>
              <span>添加任务</span>
            </el-button>
            <el-button type="primary" @click="startTask">
              <i class="el-icon iconfont icon-zhuanshukefu"></i>
              <span>开始任务</span>
            </el-button>
            <el-button type="primary" @click="stopTask">
              <i class="el-icon iconfont icon-zhuanshukefu"></i>
              <span>停止任务</span>
            </el-button>
            <el-button type="primary" @click="delTask">
              <i class="el-icon iconfont icon-zhuanshukefu"></i>
              <span>删除任务</span>
            </el-button>
            <el-button type="primary" @click="getSelect">
              <i class="el-icon iconfont icon-zhuanshukefu"></i>
              <span>获取所有选中的数据</span>
            </el-button>
          </div>
          <div style="margin-top: 24px">
            <vxe-table
              align="center"
              :size="configStore.getTableSize"
              ref="taskTableRef"
              border
              :row-config="{ isHover: true }"
              :data="tableData"
              :radio-config="{ labelField: 'name', highlight: true }"
              @radio-change="radioChangeEvent1"
            >
              <vxe-column type="radio" title="任务名称" width="250" show-overflow></vxe-column>
              <vxe-column field="progress" title="进度">
                <template #default="{ row }">
                  <div style="display: flex; flex-direction: row; align-items: center; gap: 12px">
                    <div style="flex: 1">
                      <el-progress
                        :percentage="
                          row.process.count1 == 0
                            ? '0'
                            : Math.floor((row.process.count2 / row.process.count1) * 100)
                        "
                        :color="customColors"
                        :show-text="false"
                      ></el-progress>
                    </div>
                    <span style="width: 46px"
                      >{{
                        row.process.count1 == 0
                          ? '0'
                          : Math.floor((row.process.count2 / row.process.count1) * 100)
                      }}%</span
                    >
                  </div>
                </template>
              </vxe-column>
              <vxe-column field="created_at" title="创建时间" :formatter="formatTime"></vxe-column>
            </vxe-table>
            <div style="display: flex; justify-content: center; margin-top: 24px">
              <el-pagination
                @update:current-page="handleTaskPageChange"
                :default-page-size="5"
                :total="taskTotal"
                size="small"
                background
                layout="prev, pager, next"
                class="mt-4"
              />
            </div>
          </div>
        </div>
      </el-card>
      <el-card>
        <template #header>
          <div class="card-header">
            <span>在线店铺列表</span>
          </div>
        </template>
        <vxe-table
          align="center"
          :size="configStore.getTableSize"
          ref="shopTableRef"
          border
          :row-config="{ isHover: true }"
          :data="loginUsers"
          :radio-config="{ labelField: 'name', highlight: true }"
          @radio-change="radioChangeEvent2"
        >
          <vxe-column type="radio" title="账号" width="250" show-overflow></vxe-column>
          <vxe-column field="shop_name" title="店铺名称" show-overflow></vxe-column>
          <vxe-column field="zdyfmb" title="运费模板">
            <template #default="{ row }">
              {{ row.zdyfmb ? JSON.parse(row.zdyfmb).text : '-' }}
            </template>
          </vxe-column>
          <vxe-column title="设置运费模板">
            <template #default="{ row }">
              <el-button type="primary" size="small" @click="settingYfmb(row)">
                <span>{{ row.zdyfmb ? '重设运费' : '指定运费' }}</span>
              </el-button>
            </template>
          </vxe-column>
        </vxe-table>
      </el-card>
      <el-card>
        <template #header>
          <div class="card-header">
            <span>任务执行列表</span>
          </div>
        </template>
        <vxe-table
          align="center"
          :size="configStore.getTableSize"
          ref="userTaskTableRef"
          border
          :row-config="{ isHover: true }"
          :data="userTaskData"
          :radio-config="{ labelField: 'id', highlight: true }"
        >
          <vxe-column
            field="good"
            title="源商品ID"
            width="120"
            align="center"
            show-overflow
            :formatter="formatterGoodId"
          ></vxe-column>
          <vxe-column title="任务进度" width="120">
            <template #default="{ row }">
              <vxe-tag v-if="row.zt === 0" status="info">导入成功</vxe-tag>
              <vxe-tag v-if="row.zt === 1" status="success">已运行</vxe-tag>
              <vxe-tag v-if="row.zt === 2" status="primary">已暂停</vxe-tag>
            </template>
          </vxe-column>
          <vxe-column title="执行结果" width="120">
            <template #default="{ row }">
              <vxe-tag v-if="row.result.includes('200')" status="success">执行成功</vxe-tag>
              <vxe-tag v-else-if="row.result.includes('400')" status="error">执行失败</vxe-tag>
              <vxe-tag v-else-if="row.result === ''" status="warning">未执行</vxe-tag>
            </template>
          </vxe-column>

          <vxe-column field="params" align="center" title="运行参数" show-overflow></vxe-column>
          <vxe-column
            align="center"
            width="100"
            field="created_at"
            title="创建时间"
            show-overflow
            :formatter="formatTime"
          ></vxe-column>
        </vxe-table>
        <div style="display: flex; justify-content: center; margin-top: 24px">
          <el-pagination
            @update:current-page="handleUserTaskPageChange"
            :default-page-size="10"
            :total="userTaskTotal"
            size="small"
            background
            layout="prev, pager, next"
            class="mt-4"
          />
        </div>
      </el-card>
    </div>
    <el-dialog
      v-model="yfDialogVisible"
      title="运费模板设置"
      width="600px"
      :before-close="cancelYfForm"
    >
      <div class="yfmb-container">
        <div
          style="
            display: flex;
            margin: 12px 0px;
            margin-bottom: 12px;
            justify-content: space-between;
            width: 100%;
          "
        >
          <el-input v-model="keyword" placeholder="请输入关键词" class="ml-2" style="flex: 1" />
          <div style="width: 60px; margin-left: 12px">
            <el-button type="primary" @click="search">搜索</el-button>
          </div>
        </div>
        <div
          style="
            max-height: 400px;
            min-height: 400px;
            overflow-y: scroll;
            border: 1px solid #eee;
            padding: 12px 0;
            border-radius: 8px;
          "
        >
          <el-radio-group v-model="yfRadio">
            <el-radio v-for="item in yfmbList" :key="item.value" :value="item">{{
              item.text
            }}</el-radio>
          </el-radio-group>
        </div>
      </div>

      <template #footer>
        <el-button @click="cancelYfForm">取消</el-button>
        <el-button type="primary" @click="saveYfmb">确定</el-button>
      </template>
    </el-dialog>
    <!-- 添加任务弹窗 -->
    <el-dialog v-model="dialogVisible" title="添加任务" width="600px" :before-close="cancelForm">
      <el-form
        :model="form"
        label-width="100px"
        style="padding: 20px 0"
        :rules="rules"
        ref="formRef"
      >
        <el-form-item label="上传文件" prop="file">
          <div style="display: flex; align-items: start; flex-direction: column; width: 100%">
            <el-button type="primary" @click="chooseFile">
              <i class="el-icon iconfont icon-zhuanshukefu"></i>
              <span>选择文件</span>
            </el-button>
            <div v-if="form.fileInfo" class="file-info">
              <p>已选择文件: {{ form.fileInfo.name }}</p>
              <p>文件路径: {{ form.fileInfo.path }}</p>
              <p>文件行数: {{ fileLineCount }} 行</p>
              <div class="file-content" v-if="fileContent">
                <p>文件内容预览:</p>
                <pre>{{ fileContentPreview }}</pre>
              </div>
            </div>
          </div>
        </el-form-item>
        <el-form-item label="上货模板" prop="select1">
          <el-select
            v-model="form.select1"
            props="{value: 'id', label: 'name'}"
            placeholder="请选择上货模板"
          >
            <el-option v-for="item in useMbs" :key="item.id" :label="item.name" :value="item.id" />
          </el-select>
        </el-form-item>

        <el-form-item label="关联店铺" prop="select2">
          <el-select
            v-model="form.select2"
            props="{value: 'id', label: 'name'}"
            multiple
            placeholder="请选择关联店铺"
          >
            <el-option
              v-for="item in loginUsers"
              :key="item.value"
              :label="item.name"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
      </el-form>

      <template #footer>
        <el-button @click="cancelForm">取消</el-button>
        <el-button type="primary" @click="submitForm">确定</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import XEUtils from 'xe-utils'
import { useConfigStore } from '../stores/config'

let keyword = ref('')
const search = () => {
  if (keyword.value) {
    yfmbList.value = yfmbList.value.filter((item) => item.text.includes(keyword.value))
  } else {
    yfmbList.value = copyData.value
  }
}
const yfmbList = ref([])
const yfDialogVisible = ref(false)
const yfRadio = ref()
const yfShopId = ref()
let copyData = ref([])
const settingYfmb = (row) => {
  console.log('row:', row)
  yfShopId.value = row.id
  yfDialogVisible.value = true
  yfmbList.value = row.yfmb
    ? JSON.parse(row.yfmb)[0].name == 'template'
      ? JSON.parse(row.yfmb)[0].dataSource
      : []
    : []
  copyData.value = JSON.parse(JSON.stringify(yfmbList.value))
}

const saveYfmb = async () => {
  console.log('yfRadio:', yfRadio.value)
  let result = await window.electronAPI.settingYfmb(yfShopId.value, JSON.stringify(yfRadio.value))
  if (result) {
    ElMessage.success('设置成功')
    yfDialogVisible.value = false
    await getLoginUsers()
    // 刷新数据
  } else {
    ElMessage.error('设置失败')
  }
  keyword.value = ''
}

// 获取配置store
const configStore = useConfigStore()

const stopTask = () => {
  // 停止任务
  const $table = taskTableRef.value
  if ($table) {
    const currRow = $table.getRadioRecord()
    if (!currRow) {
      ElMessage.error('请选择一个任务')
      return
    }
    // 开始任务
    window.electronAPI.stopTask(currRow.id)
    ElMessage.success('任务已停止')
  }
}

const formatterGoodId = ({ cellValue }) => {
  console.log('good:', cellValue)
  return cellValue.match(/id=(\d+)/)[1]
}
const taskTableRef = ref(null)
const shopTableRef = ref(null)

const selectedTaskData = ref([])
const selectedShopData = ref([])

let taskPage = ref(1)
let taskTotal = ref(0)

let userTaskPage = ref(1)
let userTaskTotal = ref(0)

const getSelectedData = () => {
  console.log('taskTableRef', taskTableRef.value)
  if (taskTableRef.value) {
    const records = taskTableRef.value.getRadioRecord()
    selectedTaskData.value = records
  }
  if (shopTableRef.value) {
    const records = shopTableRef.value.getRadioRecord()
    selectedShopData.value = records
  }
}
const getUserTasks = async () => {
  console.log(
    'getUserTasks 参数:',
    selectedShopData.value && selectedShopData.value.id ? selectedShopData.value.id : null,
    selectedTaskData.value && selectedTaskData.value.id ? selectedTaskData.value.id : null,
    userTaskPage.value
  )
  let data = await window.electronAPI.getUserTask(
    selectedShopData.value && selectedShopData.value.id ? selectedShopData.value.id : null,
    selectedTaskData.value && selectedTaskData.value.id ? selectedTaskData.value.id : null,
    userTaskPage.value
  )
  return data
}
const radioChangeEvent1 = async ({ row }) => {
  getSelectedData()
  console.log('选中的数据:', selectedTaskData.value, selectedShopData.value)
  let data = await getUserTasks()
  console.log('data:', data)
  userTaskData.value = data.tasks
  userTaskTotal.value = data.total
}
const radioChangeEvent2 = async ({ row }) => {
  getSelectedData()
  console.log('选中的数据:', selectedTaskData.value, selectedShopData.value)
  let data = await getUserTasks()
  console.log('data:', data)
  userTaskData.value = data.tasks
  userTaskTotal.value = data.total
}
const getSelect = () => {
  getSelectedData()
  console.log('选中的数据:', selectedTaskData.value, selectedShopData.value)
}

const startTask = () => {
  const $table = taskTableRef.value
  if ($table) {
    const currRow = $table.getRadioRecord()
    if (!currRow) {
      ElMessage.error('请选择一个任务')
      return
    }
    // 开始任务
    window.electronAPI.startTask(currRow.id)
    ElMessage.success('任务开始')
  }
}

const handleTaskPageChange = async (e) => {
  taskPage.value = e
  await getTaskData()
}
const handleUserTaskPageChange = async (e) => {
  console.log(
    'handleUserTaskPageChange 选中的数据:',
    selectedTaskData.value,
    selectedShopData.value
  )
  userTaskPage.value = e
  let data = await getUserTasks()
  userTaskData.value = data.tasks
  userTaskTotal.value = data.total
}
const loginUsers = ref([])
const getLoginUsers = async () => {
  let data = await window.electronAPI.getLogin()
  loginUsers.value = data
}

const useMbs = ref([])
const getAllMbs = async () => {
  let data = await window.electronAPI.getAllMbs()
  console.log('data:', data)
  useMbs.value = data
}

const formatTime = ({ cellValue }) => {
  return XEUtils.toDateString(cellValue, 'yyyy-MM-dd')
}
const fileList = ref([])
let tableData = ref([])

const userTaskData = ref([])

const dialogVisible = ref(false)
const form = ref({
  file: '',
  select1: '',
  select2: ''
})

const rules = {
  file: [{ required: true, message: '请选择文件', trigger: 'change' }],
  select1: [{ required: true, message: '请选择上货模板', trigger: 'change' }],
  select2: [{ required: true, message: '请选择关联店铺', trigger: 'change' }]
}

onMounted(async () => {
  await getTaskData()
  getLoginUsers()
  getAllMbs()
})

const getTaskData = async () => {
  let data = await window.electronAPI.getTasks(taskPage.value, 5, '')
  console.log('data111:', data)
  taskTotal.value = data.total
  tableData.value = data.tasks
}

// 添加任务方法
const addTask = () => {
  dialogVisible.value = true
}
const formRef = ref(null)
// 提交表单
const submitForm = async () => {
  if (fileLineCount.value === 0) {
    ElMessage.warning('请选择文件')
    return
  }
  // 验证表单
  // 获取档期时间，yyyy-MM-dd_HH:mm:ss
  let date = new Date()
  let year = date.getFullYear()
  let month = date.getMonth() + 1
  let day = date.getDate()
  let hour = date.getHours()
  let minute = date.getMinutes()
  let second = date.getSeconds()
  let time = `${year}-${month}-${day}_${hour}:${minute}:${second}`
  formRef.value.validate(async (valid) => {
    if (valid) {
      // 表单验证通过，提交数据到后端或进行其他操作
      console.log('form.value', form.value)
      let result = await window.electronAPI.addTask(
        form.value.file,
        `${time}_${form.value.fileInfo.name}`,
        form.value.select1, // 模板id
        form.value.select2.toString() // 用户
      )
      console.log('result:', result)
      ElMessage.success(result.message || '任务添加成功')
      clearForm()
      dialogVisible.value = false
      getTaskData()
    }
  })
}

// 取消表单
const cancelForm = () => {
  clearForm()
  dialogVisible.value = false
  yfDialogVisible.value = false
}
const cancelYfForm = () => {
  clearYfForm()
  yfDialogVisible.value = false
  keyword.value = ''
}
const clearYfForm = () => {
  yfRadio.value = ''
  yfShopId.value = ''
}
// 清空表单数据
const clearForm = () => {
  form.value = {
    file: null,
    select1: '',
    select2: '',
    fileInfo: null
  }
  fileList.value = []
  formRef.value.resetFields()
}

// 文件内容和行数
const fileContent = ref('')
const fileLineCount = ref(0)
const fileContentPreview = ref('')

const chooseFile = async () => {
  try {
    // 调用主进程API打开文件选择器
    const result = await window.electronAPI.chooseFile()
    console.log('文件选择结果:', result)

    if (result.success) {
      // 更新表单数据
      form.value.fileInfo = {
        name: result.filePath.split('\\').pop(),
        path: result.filePath
      }

      // 存储文件内容和行数
      fileContent.value = result.content
      fileLineCount.value = result.lineCount

      // 生成内容预览（前5行）
      if (result.content) {
        const lines = result.content.split('\n')
        fileContentPreview.value = lines.slice(0, 5).join('\n')
        if (lines.length > 5) {
          fileContentPreview.value += '\n... 更多内容省略 ...'
        }
      }
      form.value.file = result.filePath
      ElMessage.success('文件选择成功')
    } else {
      ElMessage.warning(result.message || '未选择文件')
    }
  } catch (error) {
    console.error('选择文件时出错:', error)
    ElMessage.error('选择文件时出错')
  }
}
</script>

<style scoped>
.el-container {
  width: 100% !important;
}
.el-aside {
  flex: 2 !important;
}
.file-info {
  margin-top: 10px;
  padding: 10px;
  border: 1px solid #e6e6e6;
  border-radius: 4px;
  background-color: #f9f9f9;
  height: 320px;
  width: 100%;
}

.file-content {
  margin-top: 10px;
  padding: 10px;
  border: 1px solid #e6e6e6;
  border-radius: 4px;
  background-color: #fff;
  max-height: 200px;
  overflow: auto;
}

pre {
  white-space: pre-wrap;
  word-break: break-all;
  font-family: monospace;
  font-size: 12px;
  line-height: 1.5;
  margin: 0;
}
h2 {
  font-size: 18px;
  font-weight: bolder;
  color: #000;
  margin: 12px 0;
}

.yfmb-container .el-radio-group {
  align-items: flex-start;
  display: flex;
  flex-wrap: wrap;
  font-size: 0;
  flex-direction: column;
  padding-left: 24px;
  gap: 12px;
}
</style>
